﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

using ThousandFunClient.model;
using ThousandFunClient.Util;
using System.Collections;
using System.IO.Ports;
using System.Timers;
using log4net;
using System.Globalization;

namespace ThousandFunClient
{
    public partial class Fm_TCP : Form
    {
        public Fm_TCP()
        {
            InitializeComponent();

           
        }

        private Thread mythread; 
        private Socket socket;
        public void ClearResource(bool disposing) 

        { 

            try 

　         { 　　 

　　         socket.Close();//释放资源 

　　         mythread.Abort ( ) ;//中止线程 

　         } 

　         catch{ } 

         

            if( disposing ) 

            { 

                if (components != null) 

                { 

                components.Dispose(); 

                } 

            } 

            base.Dispose( disposing ); 

          } 

        public static IPAddress GetServerIP() 

        { 

            IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName()); 

            return ieh.AddressList[0]; 

        } 

        private void BeginListen() 

        { 

            IPAddress ServerIp=GetServerIP();
            IPEndPoint iep = new IPEndPoint(ServerIp, 6575); 
            socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); 
            byte[] byteMessage=new byte[100]; 
            Invoke(new MethodInvoker(delegate { label1.Text = iep.ToString(); }));
            socket.Bind(iep); 
            // do 
            socket.Listen(5);
            Socket newSocket = socket.Accept(); 
            while(true) 
            { 
                try 
                { 
                //byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
                //string welcome = "welcome here!";
                //data = Encoding.ASCII.GetBytes(welcome);
                //newSocket.Send(data, data.Length, SocketFlags.None);//发送信息
                newSocket.Receive(byteMessage);
                string sTime = DateTime.Now.ToShortTimeString ( ) ; 
                string msg=sTime+":"+"Message from:"; 
                msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage);
                Invoke(new MethodInvoker(delegate { txt_torque.Text = msg; }));
                byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
                string welcome = "welcome here!";
                data = Encoding.ASCII.GetBytes(welcome);
                newSocket.Send(data, data.Length, SocketFlags.None);//发送信息
                //this.listBox1.Items.Add(msg); 
                } 
                catch(SocketException ex) 
                {
                    Invoke(new MethodInvoker(delegate { txt_torque.Text = ex.ToString(); }));
                }
            } 
        } 

//开始监听 

            private void button1_Click(object sender, System.EventArgs e) 

            { 

                try 

                { 

                    mythread = new Thread(new ThreadStart(BeginListen)); 

                    mythread.Start(); 

                 

                } 

                catch(System.Exception er) 

                { 

                    MessageBox.Show(er.Message,"完成",MessageBoxButtons.OK,MessageBoxIcon.Stop); 

                } 

        } 

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    int recv;//用于表示客户端发送的信息长度
        //    byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
        //    IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//本机预使用的IP和端口
        //    Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //    newsock.Bind(ipep);//绑定
        //    newsock.Listen(10);//监听
        //    //Console.WriteLine("waiting for a client");
        //    Socket client = newsock.Accept();//当有可用的客户端连接尝试时执行，并返回一个新的socket,用于与客户端之间的通信
        //    IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;
        //    //Console.WriteLine("connect with client:" + clientip.Address + " at port:" + clientip.Port);
        //    string welcome = "welcome here!";
        //    data = Encoding.ASCII.GetBytes(welcome);
        //    client.Send(data, data.Length, SocketFlags.None);//发送信息
        //    while (true)
        //    {//用死循环来不断的从客户端获取信息
        //        data = new byte[1024];
        //        recv = client.Receive(data);
        //        Console.WriteLine("recv=" + recv);

        //        String recstr = Encoding.ASCII.GetString(data, 0, recv);
        //        LV_main.View = View.Details;//列的显示模式
        //        ListViewItem lvi = new ListViewItem(new string[] { recstr, recstr }, -1);
        //        LV_main.Items.Add(lvi);

        //        if (recv == 0)//当信息长度为0，说明客户端连接断开
        //            break;
        //        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
        //        client.Send(data, recv, SocketFlags.None);
        //    }
        //    Console.WriteLine("Disconnected from" + clientip.Address);
        //    client.Close();
        //    newsock.Close();
 
        //}

        private void button2_Click(object sender, EventArgs e)
        {
            int recv;
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 6075);//定义一网络端点
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
            newsock.Bind(ipep);//Socket与本地的一个终结点相关联
            Console.WriteLine("Waiting for a client..");

            IPEndPoint ipsender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
            EndPoint Remote = (EndPoint)(ipsender);//
            recv = newsock.ReceiveFrom(data, ref Remote);//接受数据           
            Console.WriteLine("Message received from{0}:", Remote.ToString());
            //Console.WriteLine(Encoding.ASCII.GetBytes(data, 0, recv));
            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            string welcome = "Welcome to my test server!";
            data = Encoding.ASCII.GetBytes(welcome);
            newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
            while (true)
            {
                data = new byte[1024];
                recv = newsock.ReceiveFrom(data, ref Remote);
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                newsock.SendTo(data, recv, SocketFlags.None, Remote);
            }
 
        }

        private void UDPBeginListen()
        {

            IPAddress ServerIp = GetServerIP();
            IPEndPoint iep = new IPEndPoint(ServerIp, 6575);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            byte[] byteMessage = new byte[100];
            Invoke(new MethodInvoker(delegate { label1.Text = iep.ToString(); }));
            socket.Bind(iep);
 
            Socket newSocket = socket.Accept();
            while (true)
            {
                try
                {
                    //byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
                    //string welcome = "welcome here!";
                    //data = Encoding.ASCII.GetBytes(welcome);
                    //newSocket.Send(data, data.Length, SocketFlags.None);//发送信息
                    newSocket.Receive(byteMessage);
                    string sTime = DateTime.Now.ToShortTimeString();
                    string msg = sTime + ":" + "Message from:";
                    msg += newSocket.RemoteEndPoint.ToString() + Encoding.Default.GetString(byteMessage);
                    Invoke(new MethodInvoker(delegate { txt_torque.Text = msg; }));
                    //this.listBox1.Items.Add(msg); 
                }
                catch (SocketException ex)
                {
                    Invoke(new MethodInvoker(delegate { txt_torque.Text = ex.ToString(); }));
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            thThreadRead = new Thread(new ThreadStart(Listen));
            thThreadRead.Start();//启动线程 
        } 


        private void Listen ( ) 
        { 
            try 
            { 
                tlTcpListen = new TcpListener ( port ) ; //以8000端口号来初始化TcpListener实例 
                tlTcpListen.Start ( ) ; //开始监听 
                tcClient = tlTcpListen.AcceptTcpClient ( ) ; //通过TCP连接请求 
                nsStream = tcClient.GetStream ( ) ; //获取用以发送、接收数据的网络基础数据流 
                srRead=new StreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例 

                while( blistener ) //循环侦听 
                { 
                    string sMessage = srRead.ReadLine();//从网络基础数据流中读取一行数据 
                    if ( sMessage == "STOP" ) //判断是否为断开TCP连接控制码 
                    { 
                        tlTcpListen.Stop(); //关闭侦听 
                        nsStream.Close(); //释放资源 
                        srRead.Close(); 
                        thThreadRead.Abort(); //中止线程 
                        return; 
                    }
                    string sTime = DateTime.Now.ToShortTimeString(); //获取接收数据时的时间 
                    Invoke(new MethodInvoker(delegate { txt_torque.Text = sMessage; }));
                }
            }
            catch (System.Security.SecurityException)
            {
                MessageBox.Show("侦听失败！", "错误");
            }
        }

        int port = 6575; //定义侦听端口号 

        private Thread thThreadRead; //创建线程，用以侦听端口号，接收信息 

        private TcpListener tlTcpListen; //侦听端口号 

        private bool blistener = true; //设定标示位，判断侦听状态 

        private NetworkStream nsStream; //创建接收的基本数据流 

        private StreamReader srRead;

        private TcpClient tcClient;

        private void button4_Click(object sender, EventArgs e)
        {
            MessageBox.Show(ConfigUtil.GetNowIPAddress());
            BeginSend();
        }

        private void BeginSend()
        {
            string ip = this.textBox1.Text;
            string port = this.textBox2.Text;
            IPAddress serverIp = IPAddress.Parse(ip);
            int serverPort = Convert.ToInt32(port);
            IPEndPoint iep = new IPEndPoint(serverIp, serverPort);
            byte[] byteMessage;
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(iep);
            byteMessage = Encoding.ASCII.GetBytes(textBox3.Text);
            socket.Send(byteMessage);
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }





        //声明将要用到的类
        private IPEndPoint ServerInfoServer;//存放服务器的IP和端口信息
        private Socket ServerSocket;//服务端运行的SOCKET
        private Thread ServerThread;//服务端运行的线程
        private Socket[] ClientSocketServer;//为客户端建立的SOCKET连接
        private int ClientNumb;//存放客户端数量
        private byte[] MsgBufferServer;//存放消息数据

        private void CmdStar_Click(object sender, EventArgs e)
        {
            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //提供一个 IP 地址，指示服务器应侦听所有网络接口上的客户端活动
            IPAddress ip = IPAddress.Any;
            ServerInfoServer = new IPEndPoint(ip, ConfigUtil.GetToolsNetPort());
            ServerSocket.Bind(ServerInfoServer);//将SOCKET接口和IP端口绑定
            ServerSocket.Listen(10);//开始监听，并且挂起数为10

            ClientSocketServer = new Socket[100];//为客户端提供连接个数
            MsgBufferServer = new byte[65535];//消息数据大小
            ClientNumb = 0;//数量从0开始统计

            ServerThread = new Thread(new ThreadStart(RecieveAccept));//将接受客户端连接的方法委托给线程
            ServerThread.Start();//线程开始运行

            CheckForIllegalCrossThreadCalls = false;//不捕获对错误线程的调用

            this.CmdStar.Enabled = false;
            this.CmdStop.Enabled = true;
            this.StateMsg.Text = "服务正在运行..." + " 运行端口：" + ConfigUtil.GetToolsNetPort().ToString();
            this.ClientList.Items.Add("服务于 " + DateTime.Now.ToString() + " 开始运行.");
        }

        //接受客户端连接的方法
        private void RecieveAccept()
        {
            while (true)
            {
                //Accept 以同步方式从侦听套接字的连接请求队列中提取第一个挂起的连接请求，然后创建并返回新的 Socket。
                //在阻止模式中，Accept 将一直处于阻止状态，直到传入的连接尝试排入队列。连接被接受后，原来的 Socket 继续将传入的连接请求排入队列，直到您关闭它。
                ClientSocketServer[ClientNumb] = ServerSocket.Accept();
                ClientSocketServer[ClientNumb].BeginReceive(MsgBufferServer, 0, MsgBufferServer.Length, SocketFlags.None,
                    new AsyncCallback(RecieveCallBack), ClientSocketServer[ClientNumb]);

                String msg = Encoding.Default.GetString(MsgBufferServer);

                lock (this.ClientList)
                {
                    this.ClientList.Items.Add(ClientSocketServer[ClientNumb].RemoteEndPoint.ToString() + " 成功连接服务器.");
                }
                ClientNumb++;
            }
        }

        //回发数据给客户端
        private void RecieveCallBack(IAsyncResult AR)
        {
            try
            {
                Socket RSocket = (Socket)AR.AsyncState;
                int REnd = RSocket.EndReceive(AR);
                //对每一个侦听的客户端端口信息进行接收和回发
                for (int i = 0; i < ClientNumb; i++)
                {
                    if (ClientSocketServer[i].Connected)
                    {
                        //回发数据到客户端
                        ClientSocketServer[i].Send(MsgBufferServer, 0, REnd, SocketFlags.None);
                    }
                    String msg = Encoding.Unicode.GetString(MsgBufferServer, 0, REnd);
                    Invoke(new MethodInvoker(delegate { txt_torque.Text = msg; }));

                    //同时接收客户端回发的数据，用于回发
                    RSocket.BeginReceive(MsgBufferServer, 0, MsgBufferServer.Length, 0, new AsyncCallback(RecieveCallBack), RSocket);
                }
            }
            catch { }

        }

        private void CmdStop_Click(object sender, EventArgs e)
        {
            ServerThread.Abort();//线程终止
            ServerSocket.Close();//关闭socket

            this.CmdStar.Enabled = true;
            this.CmdStop.Enabled = false;
            this.StateMsg.Text = "等待运行...";
            this.ClientList.Items.Add("服务于 " + DateTime.Now.ToString() + " 停止运行.");
        }

        private void ServerMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            ServerThread.Abort();//线程终止
            ServerSocket.Close();//关闭SOCKET
            Application.Exit();
        }



        private IPEndPoint ServerInfo;
        private Socket ClientSocket;
        //信息接收缓存
        private Byte[] MsgBuffer;
        //信息发送存储
        private Byte[] MsgSend;

        private void CmdEnter_Click(object sender, EventArgs e)
        {
            //定义一个IPV4，TCP模式的Socket
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            MsgBuffer = new Byte[65535];
            MsgSend = new Byte[65535];
            //允许子线程刷新数据
            CheckForIllegalCrossThreadCalls = false;

            //服务端IP和端口信息设定,这里的IP可以是127.0.0.1，可以是本机局域网IP，也可以是本机网络IP
            //ServerInfo = new IPEndPoint(IPAddress.Parse(ConfigUtil.GetToolsNetIP()), 6573);
            //ServerInfo = new IPEndPoint(IPAddress.Parse(ConfigUtil.GetToolsNetIP()), 6570);
            ServerInfo = new IPEndPoint(IPAddress.Parse(ConfigUtil.GetToolsNetIP()), 6575);

            uint IOC_IN = 0x80000000;
            uint IOC_VENDOR = 0x18000000;
            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
            byte[] outValue = BitConverter.GetBytes(0);

            
            try
            {
                //客户端连接服务端指定IP端口，Sockket
                ClientSocket.Connect(ServerInfo);
                //将用户登录信息发送至服务器，由此可以让其他客户端获知
                //ClientSocket.Send(Encoding.Unicode.GetBytes("用户： " + this.UserName.Text + " 进入系统！\n"));
                //ClientSocket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, outValue);
                //ClientSocket.Send(Encoding.Unicode.GetBytes("1"));
                //开始从连接的Socket异步读取数据。接收来自服务器，其他客户端转发来的信息
                //AsyncCallback引用在异步操作完成时调用的回调方法
               
                //string seqnum = make05str("00036") + make07str("00036");
                //byte[] array = new byte[seqnum.Length];   //定义一组数组array
                //MsgSend = System.Text.Encoding.ASCII.GetBytes(seqnum); //string转换的字母
                //ClientSocket.Send(MsgSend);
                //this.CmdSend.Enabled = true;
                //this.CmdEnter.Enabled = false;
                //this.CmdExit.Enabled = true;
                ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);

            }
            catch (Exception ex)
            {
                MessageBox.Show("登录服务器失败，请确认服务器是否正常工作！");
            }
        }
        private Socket pClientSocket;

        private void ReceiveCallBackpri(IAsyncResult AR)
        {
            string retseqstr = "";
            try
            {
                //结束挂起的异步读取，返回接收到的字节数。 AR，它存储此异步操作的状态信息以及所有用户定义数据
                int REnd = pClientSocket.EndReceive(AR);
                byte[] brec = new byte[REnd];
                for(int i=0;i<REnd;i++) 
                {
                    brec[i] = MsgBuffer[i];
                }
                lock (this.RecieveMsg)
                {
                    Constants.syslogger.Error("receive");
                    Constants.syslogger.Error(brec);
                    retseqstr = System.Text.Encoding.ASCII.GetString(brec);
                    Constants.syslogger.Error(retseqstr);
                    //Constants.syslogger.Error(MsgBuffer);
                    this.RecieveMsg.AppendText(Encoding.Unicode.GetString(MsgBuffer, 0, REnd));

                }
            }
            catch (Exception ex)
            {
                Constants.syslogger.Error(ex);
                MessageBox.Show("已经与服务器断开连接！");
                this.Close();
            }

        }

        private string retseqstr = "";
        private void ReceiveCallBack(IAsyncResult AR)
        {
            
            try
            {
                //结束挂起的异步读取，返回接收到的字节数。 AR，它存储此异步操作的状态信息以及所有用户定义数据
                int REnd = ClientSocket.EndReceive(AR);
                byte[] brec = new byte[REnd];
                for(int i=0;i<REnd;i++) 
                {
                    brec[i] = MsgBuffer[i];
                }
                lock (this.RecieveMsg)
                {
                    Constants.syslogger.Error("receive");
                    Constants.syslogger.Error(brec);
                    retseqstr = System.Text.Encoding.ASCII.GetString(brec);
                    Constants.syslogger.Error(retseqstr);
                    //Constants.syslogger.Error(MsgBuffer);
                    this.RecieveMsg.AppendText(Encoding.Unicode.GetString(MsgBuffer, 0, REnd));

                }

                //ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);

                string seqnum = makelenstr(make05str(retseqstr.Substring(6, 5)));//+ make07str(retseqstr.Substring(6, 5))
                
                byte[] array = new byte[seqnum.Length];   //定义一组数组array
                MsgSend = System.Text.Encoding.ASCII.GetBytes(seqnum); //string转换的字母
                string seqnum07 = makelenstr(make07str(retseqstr.Substring(6, 5)));
                byte[] MsgSend07 = System.Text.Encoding.ASCII.GetBytes(seqnum07);

                ////ClientSocket.Connect();
                ////Socket Socketcc;
                ////Invoke(new MethodInvoker(delegate { ClientSocket.Send(MsgSend); }));

                ////string seqnumc = makelenstr(make07str(retseqstr.Substring(6, 5)));//+ make07str(retseqstr.Substring(6, 5))

                
                ClientSocket.Send(MsgSend);
                ClientSocket.Send(MsgSend07);
                ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);



                //pClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //CheckForIllegalCrossThreadCalls = false;
                //IPEndPoint  pServerInfo = new IPEndPoint(IPAddress.Parse(ConfigUtil.GetToolsNetIP()), 6575);
                //try
                //{
                //    pClientSocket.Connect(pServerInfo);
                //    pClientSocket.Send(MsgSend);
                //    pClientSocket.Send(MsgSend07);

                //    pClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBackpri), null);

                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show("登录服务器失败，请确认服务器是否正常工作！");
                //}
                //Socketcc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //CheckForIllegalCrossThreadCalls = false);
                //ServerInfo = new IPEndPoint(IPAddress.Parse(ConfigUtil.GetToolsNetIP()), 6575);
                //Socketcc.Connect(ServerInfo);
                //Socketcc.Send(MsgSend);
                //Socketcc.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);
                //Invoke(new MethodInvoker(delegate { ClientSocket.Send(MsgSend); }));

                //ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
            }
            catch(Exception ex)
            {
                Constants.syslogger.Error(ex);
                MessageBox.Show("已经与服务器断开连接！");
                this.Close();
            }

        }

       

        private string makelenstr(string str)
        {
            string retstr;
            int c = str.Length;
            string addstr;
            addstr = "0000"+c.ToString();
            addstr = addstr.Substring(addstr.Length - 4, 4);
            retstr =addstr +str;

            return retstr;
        }

        private string make05str(string seqnum)
        {
            string send05str = "05" + seqnum + System.DateTime.Now.ToString("yyyyMMddhhmmss")+"000";// "20130117131322";
            return send05str;
        }

        private string make07str(string seqnum)
        {
            string send07str = "07" + seqnum + "000300010002";
            return send07str;
        }
   
        //点击发送之后没有直接添加到信息列表中，而是传到服务器，由服务器转发给每个客户端
        private void CmdSend_Click(object sender, EventArgs e)
        {
            MsgBuffer = new Byte[65535];
            MsgSend = new Byte[65535];
            string seqnum = makelenstr(make05str(retseqstr.Substring(6, 5)));//+ make07str(retseqstr.Substring(6, 5))

            byte[] array = new byte[seqnum.Length];   //定义一组数组array
            MsgSend = System.Text.Encoding.ASCII.GetBytes(seqnum); //string转换的字母
            string seqnum07 = makelenstr(make07str(retseqstr.Substring(6, 5)));

            byte[] MsgSend07 = System.Text.Encoding.ASCII.GetBytes(seqnum07);

            if (ClientSocket.Connected)
            {
                ClientSocket.Send(MsgSend07);
            }

            //MsgBuffer = new Byte[65535];
            //MsgSend = new Byte[65535];

            //CheckForIllegalCrossThreadCalls = false;

            //ServerInfo = new IPEndPoint(IPAddress.Parse(ConfigUtil.GetToolsNetIP()), 6575);

            //ClientSocket.Connect(ServerInfo);
            

            ////Invoke(new MethodInvoker(delegate { ClientSocket.Send(MsgSend); }));

            ////string seqnumc = makelenstr(make07str(retseqstr.Substring(6, 5)));//+ make07str(retseqstr.Substring(6, 5))


            
            //ClientSocket.Send(MsgSend07);
            ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
            //byte[] array = new byte[this.SendMsg.Text.Length];   //定义一组数组array
            //MsgSend = System.Text.Encoding.ASCII.GetBytes(this.SendMsg.Text); //string转换的字母

            //ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
           
            //CheckForIllegalCrossThreadCalls = false;

            //ServerInfo = new IPEndPoint(IPAddress.Parse(ConfigUtil.GetToolsNetIP()), 6575);
            
      
            //    //客户端连接服务端指定IP端口，Sockket
            //    ClientSocket.Connect(ServerInfo);
            //    //将用户登录信息发送至服务器，由此可以让其他客户端获知
            //    //ClientSocket.Send(Encoding.Unicode.GetBytes("用户： " + this.UserName.Text + " 进入系统！\n"));

            //    ClientSocket.Send(MsgSend);
            ////开始从连接的Socket异步读取数据。接收来自服务器，其他客户端转发来的信息
            ////AsyncCallback引用在异步操作完成时调用的回调方法
            //    ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);


            //MsgSend = Encoding.Unicode.GetBytes(this.SendMsg.Text);
            //if (ClientSocket.Connected)
            //{
            //    //将数据发送到连接的 System.Net.Sockets.Socket。

            //    //byte[] array = new byte[MsgSend.Length];   //定义一组数组array
            //    //array = System.Text.Encoding.ASCII.GetBytes(MsgSend); //string转换的字母

            //    ClientSocket.Send(MsgSend);
            //    this.SendMsg.Text = "";
            //    Constants.syslogger.Error(MsgSend);
                
            //}
            //else
            //{
            //    ServerInfo = new IPEndPoint(IPAddress.Parse(ConfigUtil.GetToolsNetIP()), 6573);
            //    ClientSocket.Connect(ServerInfo);
            //    ClientSocket.Connect(ServerInfo);
            //    MessageBox.Show("当前与服务器断开连接，无法发送信息！");
            //}
        }

        private void CmdExit_Click(object sender, EventArgs e)
        {
            if (ClientSocket.Connected)
            {
                ClientSocket.Send(Encoding.Unicode.GetBytes(this.UserName.Text + "离开了房间！\n"));
                //禁用发送和接受
                ClientSocket.Shutdown(SocketShutdown.Both);
                //关闭套接字，不允许重用
                ClientSocket.Disconnect(false);
            }
            ClientSocket.Close();

            this.CmdSend.Enabled = false;
            this.CmdEnter.Enabled = true;
            this.CmdExit.Enabled = false;
        }

        private void RecieveMsg_TextChanged(object sender, EventArgs e)
        {
            this.RecieveMsg.ScrollToCaret();
        }

        private void SendMsg_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyValue == 13)
            {
                e.Handled = true;
                this.CmdSend_Click(this, null);
            }
        }

        private void LV_main_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void txt_torque_TextChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void StateMsg_Click(object sender, EventArgs e)
        {

        }

        private void SendMsg_TextChanged(object sender, EventArgs e)
        {

        }

        private void UserName_TextChanged(object sender, EventArgs e)
        {

        }

        private void RecieveMsg_TextChanged_1(object sender, EventArgs e)
        {

        }

        private void ClientList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
